package com.tianqu.tms.core.util;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.commons.net.util.Base64;

import sun.misc.BASE64Decoder;

public class UrlBase64Coder {  
	public final static String ENCODING = "UTF-8";  
	  
    // 加密  
    public static String encoded(String data) throws UnsupportedEncodingException {  
        byte[] b = Base64.encodeBase64URLSafe(data.getBytes(ENCODING));  
        return new String(b, ENCODING);  
    }  
  
  
    // 解密  
    public static String decode(String data) throws UnsupportedEncodingException {  
        byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));  
        return new String(b, ENCODING);  
    }  
    
    public static void main(String[] args) throws UnsupportedEncodingException {
    	String data = ImageUtils.transPicToStr("C:\\Users\\huangwei\\Desktop\\1.png");
    	System.out.println(data);
    	
    	generateImagePost(data);
    }  
    
    
    /**
	 * 将字符串转为图片
	 * 
	 * @param imgStr
	 * @return url
	 */
	public static String generateImagePost(String imgStr) {// 对字节数组字符串进行Base64解码并生成图片
		try {
			if (imgStr == null) return null;
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0)  b[i] += 256;
			}
			OutputStream out = new FileOutputStream("d:\\b.png");
			out.write(b);
			out.flush();
			out.close();
			return "";
		} catch (Exception e) {
			return null;
		}
	}
}  